import React, { useEffect, useState, useRef, useMemo } from 'react';
import { NavigationProp, RouteProp } from '@react-navigation/native';
import { useReactive } from 'ahooks';
import { StyleSheet, TouchableOpacity, View, Text, Image, TextInput } from 'react-native';
import { CommonStyle } from '../../../common/commonStyle.ts';
import { useSelector } from 'react-redux';
import { AppDispatch, RootState } from '../../../redux/store.ts';
import { Container, TextArea, ScrollView, Modal, Button, AlertDialog } from 'native-base';
import { Loading } from '../../../component/LoadingOverlay.tsx';
import { useToast } from 'react-native-toast-notifications';
import to from '../../../utils/to.ts';
import AntDesign from 'react-native-vector-icons/AntDesign';
import NoticeBar from '../../../component/NoticeBar.tsx';
import UploadMedia from '../../../component/UploadMedia.tsx';
// import healthClockRequest from '../../../request/healthClockRequest.ts';
import CascadingPicker, { TreeNode } from '../../../component/PickerCascader.tsx';
import UserRequest from '../../../request/userRequest.ts';
import HomeRequest from '../../../request/homeRequest.ts';
import Tools from '../../../utils/Tools.ts';

interface IFireDetectionProps {
  navigation: NavigationProp<any, 'fireDetection'>;
  route: RouteProp<{ fireDetection: any }, 'fireDetection'>;
}

interface IData {
  content: string;
  iconName: string;
  address: string;
  fireDesc: string;
  video: string;
  residentAddress: any;
  pickerBuildShow: boolean;
  cascader: TreeNode[]; // 选中的楼栋层数据
  cascaderData: TreeNode[]; // 楼栋层数据
  selectedBuildIds: number[]; // 选中的楼栋层ids
  params: any;
  beeperId: number;
  alarmRecord: IGetAlarmRecord[];
}

const FireDetection: React.FC<IFireDetectionProps> = ({ navigation, route }) => {
  const beeperId = useSelector((state: RootState) => state.beeperId);
  const data = useReactive<IData>({
    content: '报警须知：请勿虚假报警，否则将承担相应后果',
    iconName: 'volume-2',
    address: '',
    fireDesc: '',
    video: '',
    residentAddress: {
      name: '',
    },
    pickerBuildShow: false,
    cascader: [],
    cascaderData: [],
    selectedBuildIds: [],
    params: {},
    beeperId: beeperId,
    alarmRecord: [],
  });

  const toast = useToast();

  const [showRecordModal, setShowRecordModal] = useState(false);
  const [isTipsOpen, setIsTipsOpen] = useState(false);
  const cancelRef = useRef(null);

  const list = [
    {
      name: '所在楼层',
      type: 1,
    },
    {
      name: '详细位置',
      type: 2,
    },
    {
      name: '灾情描述',
      type: 3,
    },
    {
      name: '上传视频',
      type: 4,
    },
  ];

  const setTextAreaValue = (text: string, type: number) => {
    if (type === 2) {
      data.address = text;
    } else {
      data.fireDesc = text;
    }
  };

  const getVideoUri = (uri: string) => {
    data.video = uri;
  };

  const stateShow = (name: string, type: number) => {
    if (type === 1) {
      return (
        <TouchableOpacity
          onPress={() => {
            data.pickerBuildShow = true;
          }}
        >
          <View style={styles.ldcView}>
            <Text>{data.residentAddress?.name ? data.residentAddress?.name : '请选择栋单元层'}</Text>
            <AntDesign
              onPress={(event) => {
                event.stopPropagation(); // 阻止事件冒泡
                data.residentAddress.name = '';
              }}
              name="closecircleo"
              size={16}
              color={'#ccc'}
            ></AntDesign>
          </View>
        </TouchableOpacity>
      );
    } else if (type === 2 || type === 3) {
      const phname = '请填写' + name;
      return <TextArea autoCompleteType="off" value={type === 2 ? data.address : data.fireDesc} h={20} placeholder={phname} w="100%" onChangeText={(text) => setTextAreaValue(text, type)} />;
    } else if (type == 4) {
      return <UploadMedia mediaType={'video'} onChange={getVideoUri}></UploadMedia>;
    }
  };

  /**
   * 联动选择器选择
   * @param val
   * @param ids
   */
  const handleCascadingChange = (val: TreeNode[], ids: number[]) => {
    data.cascader = val;
    data.selectedBuildIds = ids;
    ['buildHouseNumberNames', 'buildId', 'unitId', 'floorId', 'houseNumberId', 'buildName', 'unitName', 'floorName', 'houseNumber'].forEach((item) => {
      delete data.params[item];
    });
    data.params.buildHouseNumberNames = '';
    data.cascader.forEach((item, index) => {
      data.params.buildHouseNumberNames += index === 0 ? `${item.name}` : ` ${item.name}`;
      if (item.levels === 1) data.params = { ...data.params, buildId: item.id, buildName: item.name };
      if (item.levels === 2) data.params = { ...data.params, unitId: item.id, unitName: item.name };
      if (item.levels === 3) data.params = { ...data.params, floorId: item.id, floorName: item.name };
      if (item.levels === 4) data.params = { ...data.params, houseNumberId: item.id, houseNumber: item.name };
    });
    data.residentAddress.name = data.params.buildName + '/' + data.params.unitName + '/' + data.params.floorName + '/' + data.params.houseNumber;
    data.pickerBuildShow = false;
    fetchAlarmRecord('address');
  };

  /**
   * 获取该小区楼栋层
   * @param villageId
   */
  const fetchBuildingTree = (beeperId: number) => {
    UserRequest.BuildingTree({ beeperId }).then((res) => {
      data.cascaderData = res.data;
    });
  };

  /**
   * 根据呼叫器id获取地址详情
   * @param id
   */
  const fetchAddressDetails = () => {
    Loading.show('加载中');
    HomeRequest.GetBeeperAddress({ beeperId: data.beeperId })
      .then((res) => {
        Loading.hide();
        const { villageId, villageName, linkName, phone, buildId, unitId, floorId, houseNumberId, houseNumber, buildName, unitName, floorName, relationBeeperType, relationBeeperId, harvestAddressId, beeperId } = res.data;
        data.residentAddress.name = buildName + '/' + unitName + '/' + floorName + '/' + houseNumber;
        let ids: number[] = [];
        let names: string = '';
        if (buildId) {
          ids.push(buildId);
          names += buildName;
        }
        if (unitId) {
          ids.push(unitId);
          names += ` ${unitName}`;
        }
        if (floorId) {
          ids.push(floorId);
          names += ` ${floorName}`;
        }
        if (houseNumberId) {
          ids.push(houseNumberId);
          names += ` ${houseNumber}`;
        }
        data.selectedBuildIds = ids;
        data.params = { ...data.params, beeperId, relationBeeperType, relationBeeperId, harvestAddressId, villageId, villageName, linkName, phone, buildId, unitId, floorId, houseNumberId, houseNumber, buildName, unitName, floorName, buildHouseNumberNames: names };
      })
      .catch((err) => {
        Loading.hide();
      });
  };

  // 获取消防报警记录
  const fetchAlarmRecord = (type: string) => {
    switch (type) {
      case 'beeper':
        Loading.show('加载中');
        HomeRequest.GetAlarmRecord({ beeperId: data.beeperId })
          .then((res) => {
            Loading.hide();
            if (res.data.length > 0) {
              data.alarmRecord = res.data;
              setShowRecordModal(true);
            }
          })
          .catch((err) => {
            Loading.hide();
          });
        break;

      case 'address':
        Loading.show('加载中');
        const { buildId = null, floorId = null, houseNumberId = null, unitId = null } = data.params || {};
        HomeRequest.GetAddressAlarmRecord({ buildId, floorId, houseNumberId, unitId })
          .then((res) => {
            Loading.hide();
            if (res.data.length > 0) {
              setIsTipsOpen(true);
            }
          })
          .catch((err) => {
            Loading.hide();
          });
        break;
    }
  };

  //报警弹窗操作
  const alarmClick = (type: number) => {
    switch (type) {
      case 1:
        navigation.goBack();
        break;
      case 2:
        setShowRecordModal(false);
        break;
    }
  };

  // 发送上报
  const submitOrder = () => {
    const { params, residentAddress, address, fireDesc, video, beeperId } = data;
    // return false
    if (residentAddress.name == '' && address == '') {
      toast.show('所在楼层或详细位置必须填写一个', { placement: 'bottom' });
      return false;
    }
    if (video === '' && fireDesc === '') {
      toast.show('灾情描述或上传视频必须填写一个', { placement: 'bottom' });
      return false;
    }
    const datas = {
      beeperId: beeperId,
      fireDesc: fireDesc,
      fireVideos: video ? Tools.convertFileToBase64(video) : '',
      site: address,
      buildId: params.buildId,
      buildName: params.buildName,
      unitId: params.unitId,
      unitName: params.unitName,
      floorId: params.floorId,
      floorName: params.floorName,
      houseNumberId: params.houseNumberId,
      houseNumber: params.houseNumber,
    };

    Loading.show('提交中');

    HomeRequest.SubmitAlarmOrder(datas)
      .then((res) => {
        Loading.hide();
        toast.show('提交成功', { placement: 'bottom' });
        setTimeout(() => {
          navigation.goBack();
        }, 1000);
      })
      .catch((err) => {
        Loading.hide();
        toast.show(err.msg || '提交失败', { placement: 'bottom' });
      });
  };

  useEffect(() => {
    fetchAddressDetails();
    fetchAlarmRecord('beeper');
    fetchBuildingTree(data.beeperId);
  }, []);

  const memoNoticeBar = useMemo(() => <NoticeBar content={data.content} iconName={data.iconName} isScroll={true}></NoticeBar>, []);

  return (
    <ScrollView style={styles.viewBox}>
      {memoNoticeBar}
      {list.map((item, index) => (
        <View style={styles.container} key={index}>
          <View style={styles.title}>
            <Text style={{ color: '#000', fontSize: 16 }}>{item.name}</Text>
          </View>
          <View style={styles.main}>{stateShow(item.name, item.type)}</View>
        </View>
      ))}
      <TouchableOpacity
        onPress={() => {
          submitOrder();
        }}
      >
        <View style={styles.submitBtn}>
          <Text style={{ color: 'white' }}>上 报</Text>
        </View>
      </TouchableOpacity>

      <CascadingPicker show={data.pickerBuildShow} data={data.cascaderData} selectedIds={data.selectedBuildIds} onClose={() => (data.pickerBuildShow = false)} onConfirm={handleCascadingChange} title={'选择楼栋层门牌号'} />
      <Modal isOpen={showRecordModal} size={'md'}>
        <Modal.Content maxH="400">
          <Modal.Header style={{ alignItems: 'center' }}>24小时消防报警记录</Modal.Header>
          <Modal.Body style={{ backgroundColor: '#f3f3f3' }}>
            <ScrollView>
              {data.alarmRecord.map((item, index) => (
                <View key={index} style={styles.recordView}>
                  <View style={styles.recordChildView}>
                    <Text style={styles.recordText}>报警地址</Text>
                    <Text>{item.address}</Text>
                  </View>
                  <View style={{ borderBottomWidth: 1, borderColor: '#ddd', marginVertical: 4 }}></View>
                  <View style={styles.recordChildView}>
                    <Text style={styles.recordText}>报警时间</Text>
                    <Text>{item.createDate}</Text>
                  </View>
                </View>
              ))}
            </ScrollView>
          </Modal.Body>
          <Modal.Footer style={{ justifyContent: 'space-around', width: '100%', flexDirection: 'row' }}>
            <TouchableOpacity
              style={{ flex: 1 }}
              onPress={() => {
                alarmClick(1);
              }}
            >
              <Text style={styles.textModalBtn}>放 弃 报 警</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={{ flex: 1 }}
              onPress={() => {
                alarmClick(2);
              }}
            >
              <Text style={[styles.textModalBtn, { color: CommonStyle.mainColor }]}>继 续 报 警</Text>
            </TouchableOpacity>
          </Modal.Footer>
        </Modal.Content>
      </Modal>
      <AlertDialog leastDestructiveRef={cancelRef} isOpen={isTipsOpen}>
        <AlertDialog.Content>
          <AlertDialog.Header>提示</AlertDialog.Header>
          <AlertDialog.Body>已存在相同地址报警记录，是否继续新增？</AlertDialog.Body>
          <AlertDialog.Footer>
            <Button.Group space={2}>
              <Button
                variant="unstyled"
                colorScheme="coolGray"
                onPress={() => {
                  alarmClick(1);
                }}
              >
                取消
              </Button>
              <Button
                colorScheme="green"
                onPress={() => {
                  setIsTipsOpen(false);
                }}
              >
                继续
              </Button>
            </Button.Group>
          </AlertDialog.Footer>
        </AlertDialog.Content>
      </AlertDialog>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  viewBox: {
    padding: 16,
  },
  container: {
    width: '100%',
    minHeight: 10,
    marginTop: 20,
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 10,
  },
  title: {
    marginBottom: 10,
  },
  main: {
    width: '100%',
  },
  ldcView: {
    width: '100%',
    height: 36,
    alignItems: 'center',
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingHorizontal: 10,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: '#ccc',
  },
  recordView: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 10,
    marginBottom: 10,
  },
  recordChildView: {
    height: 50,
    justifyContent: 'center',
  },
  recordText: {
    color: '#000',
    marginBottom: 4,
    fontWeight: 'bold',
  },
  textModalBtn: {
    fontWeight: 'bold',
    textAlign: 'center',
  },
  lineText: {
    width: 1,
    fontSize: 16,
    marginHorizontal: 40,
    borderRightWidth: 1,
    borderColor: '#ccc',
  },
  submitBtn: {
    width: '80%',
    backgroundColor: CommonStyle.mainColor,
    alignItems: 'center',
    justifyContent: 'center',
    height: 40,
    borderRadius: 8,
    position: 'relative',
    left: '10%',
    right: 0,
    bottom: 30,
  },
});

export default FireDetection;
